﻿#include "WaitForConect.h"

static WaitForConnectLayer* _WaitForConnectLayer = nullptr;
static std::mutex WiatLayerLock;
WaitForConnectLayer::WaitForConnectLayer()
{
	ChangeImageTimer = 0.5f;
	_WaitForConnectLayer = this;
	VisableSize = Director::sharedDirector()->getVisibleSize();
	NeedToDisappear = false;
}

WaitForConnectLayer::~WaitForConnectLayer(){}

WaitForConnectLayer* WaitForConnectLayer::GetInstance()
{
	if (_WaitForConnectLayer == nullptr)
	{
		ThreadLocker Locker(WiatLayerLock);
		if (!_WaitForConnectLayer)
			_WaitForConnectLayer = new WaitForConnectLayer();
	}
	return _WaitForConnectLayer;
}

bool WaitForConnectLayer::init()
{
	bool bRef = false;
	do
	{
		CC_BREAK_IF(!Layer::init());
		//ReLoadAllData();

		bRef = true;
	} while (0);


	return bRef;
}

void WaitForConnectLayer::ReLoadAllData(std::string _text)
{
	removeAllChildrenWithCleanup(true);
	ChangeImageTimer = 0.5f;
	LoadingFrame = Sprite::create("Loading_Frame.png");
	LoadingFrame->SetPosition(VisableSize.x / 2, VisableSize.y / 2);
	addChild(LoadingFrame);
	Loading = Sprite::create("Loading.png");
	Loading->setScale(0.3f);
	Loading->setPosition(LoadingFrame->getContentSize().width * 0.1 + Loading->getBoundingBox().size.width / 2, LoadingFrame->getContentSize().height / 2);
	LoadingFrame->addChild(Loading);

	if (_text.empty())
		_text = "Waiting For Connect";
	Text = LabelTTF::create(_text.c_str(), "Airal", 12);
	Text->setPosition(LoadingFrame->getContentSize().width / 2, LoadingFrame->getContentSize().height / 2);
	LoadingFrame->addChild(Text);
	scheduleUpdate();
}

void WaitForConnectLayer::Show(std::string _text)	
{
	ReLoadAllData(_text.c_str());
	ConnectTotalTime = 0;
	setVisible(true); 
}

void WaitForConnectLayer::SetStringDisappearDelay(std::string _string, float time)
{
	if (!isVisible())
		return;
	if (Text)
	{
		Text->setString(_string.c_str());
	}
	if (time)
	{
		ConnectTotalTime = 5.0f - time;
		NeedToDisappear = true;
	}
}

void WaitForConnectLayer::SetStringAndResetTime(std::string _string)
{
	if (!isVisible())
		return;
	if (Text)
	{
		Text->setString(_string.c_str());
		ConnectTotalTime = 0;
	}
}

void WaitForConnectLayer::update(float diff)
{
	if (Loading)
	{
		ConnectTotalTime += diff;
		if (ConnectTotalTime > 5.0f)
		{
			if (NeedToDisappear)
				Disappear();
			else
				Text->setString("Time Out");
		}
		if (ConnectTotalTime > 6.0f)
			Disappear();
		if (ChangeImageTimer <= diff)
		{
			float ro = Loading->getRotation();
			Loading->setRotation(ro - 45.0f);
			ChangeImageTimer = 0.2f;
		}
		else ChangeImageTimer -= diff;
	}
}